package com.wtwd.wtwddevice.listener.deviceServerMsg.handler.impl;


import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.*;
import com.wtwd.device.model.BloodOxygen;
import com.wtwd.device.model.vo.AppDeviceSleepRecordInfoVo;
import com.wtwd.device.model.vo.AppDeviceSleepRecordVo;
import com.wtwd.device.model.vo.AppFrequencyVo;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.AppProtocol;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.DateUtils;
import com.wtwd.device.util.StringUtils;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.model.entity.DeviceSleepRecord;
import com.wtwd.wtwddevice.model.entity.DeviceSleepRecordInfo;
import com.wtwd.wtwddevice.mq.PushMsgService;
import com.wtwd.wtwddevice.service.IAppCommService;
import com.wtwd.wtwddevice.service.IDeviceService;
import com.wtwd.wtwddevice.service.IDeviceSleepRecordInfoService;
import com.wtwd.wtwddevice.service.IDeviceSleepRecordService;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@MsgType(MsgTypeEnum.W_SLEEPRAWDATA)
@Component
public class WSleepRawDataHandlerImpl implements IMsgHandler {

    @Resource
    private IDeviceSleepRecordService deviceSleepRecordService;

    @Resource
    private IDeviceSleepRecordInfoService deviceSleepRecordInfoService;

    @Resource
    private IAppCommService appCommService;

    @Resource
    private IDeviceService deviceService;

    @Resource
    private PushMsgService msgService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleMsg(MessageBase messageBase) {
        WTProtocol wtProtocol = messageBase.getWtProtocol();
        String body = wtProtocol.getBody();
        String[] split = body.split(SeparatorConstant.POUND_SIGN);
        String isSleep = split[0];//是否睡眠 true 1 false 0
        if (isSleep.equals("0")) return;
        String startTime = getTime(Integer.valueOf(split[1]));//开始睡眠时间
        String endTime = getTime(Integer.valueOf(split[2]));//结束睡眠时间
        Integer deepSleepLen = Integer.valueOf(split[3]);//深睡时长 单位分钟
        Integer lightSleepLen = Integer.valueOf(split[4]);//浅睡时长(分钟)
        Integer wakeUpLen = Integer.valueOf(split[5]);//清醒时长(分钟)
        Integer remSleepLen = Integer.valueOf(split[6]);//REM(快速动眼)时长(分钟)
        Integer sleepStageCount = Integer.valueOf(split[7]);//睡眠分期个数
        Long deviceId = deviceService.getDeviceIdByImei(wtProtocol.getImei());
        DeviceSleepRecord deviceSleepRecord = new DeviceSleepRecord();
        deviceSleepRecord.setDeviceId(deviceId);
        deviceSleepRecord.setStartTime(startTime);
        deviceSleepRecord.setEndTime(endTime);
        deviceSleepRecord.setDeepSleepLen(deepSleepLen);
        deviceSleepRecord.setLightSleepLen(lightSleepLen);
        deviceSleepRecord.setWakeUpLen(wakeUpLen);
        deviceSleepRecord.setRemSleepLen(remSleepLen);
        deviceSleepRecord.setNumber(wtProtocol.getNumber());
        deviceSleepRecord.setUploadTime(wtProtocol.getTime());
        deviceSleepRecord.setTime(DateUtils.format(new Date(getStartOfYesterdayUsingCalendar()), DateUtils.dateFormat15));
        deviceSleepRecord.setSleepStageCount(sleepStageCount);
        deviceSleepRecord = deviceSleepRecordService.synchronousSleepRecord(deviceSleepRecord);
        String sleepinfos = split[8];
        AppDeviceSleepRecordVo appDeviceSleepRecordVo = new AppDeviceSleepRecordVo();
        if (StringUtils.isNotEmpty(sleepinfos)) {
            List<DeviceSleepRecordInfo> deviceSleepRecordInfos = new ArrayList<>();
            List<AppDeviceSleepRecordInfoVo> appDeviceSleepRecordInfoVos = new ArrayList<>();
            String[] data = sleepinfos.split(SeparatorConstant.EXCLAMATION_MARK);//分割之后有多组信息
            for (Integer i = 0; i < sleepStageCount; i++) {
                String[] infoDate = data[i].split(SeparatorConstant.CMD_BODY_SEGMENTATION);
                DeviceSleepRecordInfo deviceSleepRecordInfo = new DeviceSleepRecordInfo();
                deviceSleepRecordInfo.setStartTime(getTime(Integer.valueOf(infoDate[0])));
                deviceSleepRecordInfo.setEndTime(getTime(Integer.valueOf(infoDate[1])));
                deviceSleepRecordInfo.setType(Integer.valueOf(infoDate[2]));
                deviceSleepRecordInfo.setDeviceSleepRecordId(deviceSleepRecord.getId());
                deviceSleepRecordInfos.add(deviceSleepRecordInfo);
                AppDeviceSleepRecordInfoVo appDeviceSleepRecordInfoVo = new AppDeviceSleepRecordInfoVo();
                BeanUtils.copyProperties(deviceSleepRecordInfo, appDeviceSleepRecordInfoVo);
                appDeviceSleepRecordInfoVos.add(appDeviceSleepRecordInfoVo);
                if (deviceSleepRecordInfos != null && deviceSleepRecordInfos.size() > 0) {
                    deviceSleepRecordInfoService.saveBatch(deviceSleepRecordInfos);
                }
                appDeviceSleepRecordVo.setInfoVos(appDeviceSleepRecordInfoVos);
            }

        }
        wtProtocol.setTime(DateUtils.format(new Date(), DateUtils.dateFormat15));
        wtProtocol.setBody(String.valueOf(AnswerStateEnum.NORMAL.getState()));
        wtProtocol.setBodyLength(wtProtocol.getBody().length());
        wtProtocol.setMesType(CmdTypeEnum.REPORT_RESPONSE.getCmdType().toString());
        msgService.pushToDevice(messageBase.getForm(),
                MessageBase.builder().deviceKey(wtProtocol.getImei())
                        .wtProtocol(wtProtocol)
                        .build());
        //推送到app
        BeanUtils.copyProperties(deviceSleepRecord, appDeviceSleepRecordVo);
        AppProtocol appProtocol = AppProtocol.builder()
                .imei(wtProtocol.getImei())
                .cmdName(MsgTypeEnum.PUSH_SLEEP_DATA_APP.getCmdName())
                .data(appDeviceSleepRecordVo)
                .build();
        appCommService.pushDeviceState(deviceId, appProtocol);

    }

    /**
     * 用于获取睡眠的起始时间结束时间
     *
     * @param time
     * @return
     */
    private static String getTime(Integer time) {
        long dayBefore = getStartOfYesterdayUsingCalendar();
        long date = dayBefore + (time * 60 * 1000);
        return DateUtils.format(new Date(date), DateUtils.dateFormat15);
    }


    public static long getStartOfYesterdayUsingCalendar() {
        Calendar calendar = Calendar.getInstance();
        // 将时间设置为今天零点
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 减去一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        return calendar.getTimeInMillis();
    }


    public static void main(String[] args) {
        System.out.println( "0".equals("0"));

    }

}
